package com.pur.zsms.photomanage.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.FileUtill;
import com.pur.zsms.common.util.ImageResizer;
import com.pur.zsms.documentsmanage.vo.DomVo;
import com.pur.zsms.foodmanage.food.po.FoodMaterPo;
import com.pur.zsms.foodmanage.food.service.IFoodService;
import com.pur.zsms.foodmanage.food.vo.FoodMaterVo;
import com.pur.zsms.foodmanage.food.vo.FoodVo;
import com.pur.zsms.matermanage.mater.service.IMaterService;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.ordercustommanage.vo.SelectFoodVo;
import com.pur.zsms.photomanage.po.PhotoPo;
import com.pur.zsms.photomanage.service.IPhotoService;
import com.pur.zsms.photomanage.vo.PhotoVo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;

@Controller
@RequestMapping(value = "/photo")
public class PhotoControllor {

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(PhotoControllor.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "photoService")
	private IPhotoService photoService;

	@RequestMapping(value = "/preMaterPhoto.do", method = { RequestMethod.GET })
	public ModelAndView preMaterPhoto(int materId) {
		Map map = new HashMap();
		map.put("materId", materId);
		return new ModelAndView("/photo/photoListByMater", map);
	}

	@RequestMapping(value = "/findPhoto.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findPhoto(@RequestParam(required = false) String page,
	        @RequestParam(required = false) String rows, PhotoVo photoVo, HttpSession session)
	        throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = photoService.findPhoto(pageController, photoVo);
		List<PhotoVo> photoList = new ArrayList<PhotoVo>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				PhotoVo f = new PhotoVo();
				f.setMaterId((Integer) item[0]);
				f.setPhotoId(Long.valueOf(item[1].toString()));
				f.setFistFlag((Integer) item[2]);
				f.setMaterName((String) item[3]);
				f.setContent("查看图片");
				photoList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", photoList);
		return json.toString();
	}

	@RequestMapping(value = "/preSavePhoto.do", method = { RequestMethod.GET })
	public ModelAndView preSavePhoto(int materId) {
		Map map = new HashMap();
		map.put("materId", materId);
		return new ModelAndView("/photo/addPhoto", map);
	}

	@RequestMapping(value = "/savePhoto.do", method = { RequestMethod.POST })
	@ResponseBody
	public String savePhoto(PhotoVo photoVo, HttpServletRequest request, HttpServletResponse response,
	        HttpSession session) throws Exception {
		JSONObject json1 = new JSONObject();
		MultipartFile file = photoVo.getFile();
		String temp = session.getServletContext().getRealPath(File.separator) + "temp"; // 临时目录
		File tempFile = new File(temp);
		if (!tempFile.exists()) {
			tempFile.mkdirs();
		}
		String filename1 = file.getOriginalFilename();
		String[] filename1Array = filename1.split("\\.");
		if (filename1Array.length != 2 || !filename1Array[1].equals("jpg")) {
			json1.put("success", false);
			json1.put("msg", "msg001");
			return json1.toString();
		}

		// 开始读取上传信息
		// int index = 0;
		if (file == null)
			return null;
		if (file.getSize() > 10000000) {
			throw new Exception("上传失败：文件大小不能超过10M");
		}
		// boolean flag = domService.checkFolder(photoVo);
		// if (flag) {
		// json1.put("msg", domService.getMsg());
		// json1.put("success", false);
		// return json1.toString();
		// }
		// 插入数据库
		PhotoPo photoPo = photoService.addPhotoPo(photoVo);

		// 设置路径
		String realPath = session.getServletContext().getRealPath("/");
		String photoRealPath = realPath + File.separator + "jsp" + File.separator + "ui" + File.separator
		        + "dphoto" + File.separator;
		if (file.getSize() > 0) {
			try {
				FileUtill.saveFileFromInputStream(file.getInputStream(), photoRealPath,
				        String.valueOf(photoPo.getPhotoId()) + ".jpg");
			} catch (IOException e) {
				System.out.println(e.getMessage());
				return null;
			}
		} else {
			throw new Exception("上传失败：上传文件不能为空");
		}
		// 处理图片
		String dphotoRealPath = realPath + File.separator + "jsp" + File.separator + "ui" + File.separator
		        + "dphoto" + File.separator + photoPo.getPhotoId() + ".jpg";
		String bigRealPath = realPath + File.separator + "jsp" + File.separator + "ui" + File.separator
		        + "big" + File.separator + photoPo.getPhotoId() + ".jpg";
		String midRealPath = realPath + File.separator + "jsp" + File.separator + "ui" + File.separator
		        + "mid" + File.separator + photoPo.getPhotoId() + ".jpg";
		String smallRealPath = realPath + File.separator + "jsp" + File.separator + "ui" + File.separator
		        + "small" + File.separator + photoPo.getPhotoId() + ".jpg";
		ImageResizer.resizeImage(dphotoRealPath, bigRealPath, 1000, 800);
		ImageResizer.resizeImage(dphotoRealPath, midRealPath, 490, 390);
		ImageResizer.resizeImage(dphotoRealPath, smallRealPath, 78, 65);

		json1.put("success", true);
		return json1.toString();
	}

}
